$(function () {
    $("#jqGrid").Grid({
        url: '../applyinfo/list',
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {
                label: '客户类型', name: 'applyType', width: 80, formatter: function (cellValue, cell, options) {
                    return applyTypeFormatter(cellValue, cell, options);
                }
            },
            {label: '姓名', name: 'personInfo.name', width: 80},
            {label: '手机', name: 'personInfo.mobile', width: 80},
            {
                label: '婚姻情况',
                name: 'personInfo.maritalStatus',
                width: 80,
                formatter: function (cellValue, options, cell) {
                    return maritalStatusFormatter(cellValue, cell, options);
                }
            },
            {label: '身份证号', name: 'personInfo.idCardNo', width: 80},
            {
                label: '现居住地址', name: 'personInfo.id', width: 80, formatter: function (cellValue, options, cell) {
                    let personInfo = cell.personInfo;
                    if (null == personInfo) {
                        return "";
                    }
                    return personInfo['resideAddressProvinceName'] + "-" + personInfo['resideAddressCityName'] + "-" + personInfo['resideAddressAreaName'];
                }
            },
            {
                label: '居住类型',
                name: 'personInfo.resideTypeId',
                width: 80,
                formatter: function (cellValue, options, cell) {
                    return beautifyResideTypeValue(cellValue);
                }
            },
            {label: '客户经理', name: 'promoUser.username', width: 120},
            {
                label: '操作', name: 'operation', width: 120, formatter: function (cellValue, cell, options) {
                    return buildOperationArea(cellValue, cell, options);
                }
            }
        ]
    });

    $(document)
        .off("click", ".detail-link")
        .on("click", ".detail-link", function () {
            let id = $(this).data("id");
            details(id);
            vm.show.onlyDetails = true;
        });

    $(document)
        .off("click", ".buy-history-link")
        .on("click", ".buy-history-link", function () {
            let applyNo = $(this).data("applyno");
            jumpToOrder(applyNo);
            vm.show.buyProduct = false;
        });


    function jumpToOrder(applyNo) {
        let storage = window.localStorage;
        storage.setItem("applyNo",applyNo);
        parent.vm.openTab("lht/order.html");
    }

});


function beautifyResideTypeValue(val) {
    for (let i in vm.options.resideTypeList) {
        let item = vm.options.resideTypeList[i];
        if (item.value == val && undefined != item.value) {
            return item.label;
        }
    }
    return "";
}

function applyTypeFormatter(cellValue, cell, options) {
    return cellValue === "1" ? "个人" : "企业";
}

function maritalStatusFormatter(cellValue, cell, options) {
    if (cellValue === "1") {
        return "已婚";
    }

    if (cellValue === "2") {
        return "未婚";
    }

    return "其他";
}

function buildOperationArea(cellValue, options, cell) {
    let area = "";

    area += "<a data-id='" + cell['id'] + "' data-applyno='" + cell["applyNo"] + "' class='detail-link'>查看详情</a>&nbsp;&nbsp;";
    area += "<a data-id='" + cell['id'] + "' data-applyno='" + cell["applyNo"] + "'class='buy-history-link'>已购产品</a>&nbsp;&nbsp;";

    return area;
}

let vm = new Vue({
    el: '#rrapp',
    data: {
        show: {
            person: false,
            cooperation: false,
            atUpdateAction: false,
            atAddAction: false,
            updateModal: false,
            onlyDetails: false,
            buyProduct: false
        },
        nativeAreaInfo: {
            provinceList: [],
            cityList: [],
            areaList: []
        },
        resideAreaInfo: {
            provinceList: [],
            cityList: [],
            areaList: []
        },
        workCompanyAreaInfo: {
            provinceList: [],
            cityList: [],
            areaList: []
        },
        houseAreaInfo: {
            provinceList: [],
            cityList: [],
            areaList: []
        },
        showList: true,
        title: null,
        applyInfo: buildDefApplyInfoValueObj(),
        q: {
            name: '',
            mobile: ''
        },
        genderValue: "1",
        genderArr: [],
        options: {},
        updateInfo: {
            promoUserId: null
        },
        ruleValidate: {
            "applyType": [
                {required: true, message: '请选择客户类型'}
            ],
            "promoUserId": [
                {required: true, message: '请选择客户经理'}
            ],
            "personInfo.name": [
                {required: true, message: '客户名称不能为空'}
            ],
            "personInfo.maritalStatus": [
                {required: true, message: '请选择婚姻状况'}
            ],
            "personInfo.mobile": [
                {required: true, message: '请填写电话号码'}
            ],
            "personInfo.nativeProvinceCode": [
                {required: true, message: '请填写省份'}

            ],
            "personInfo.idCardNo": [
                {required: true, message: '请填写身份证号码'}
            ],
            "personInfo.resideTypeId": [
                {required: true, message: '请选择居住类型'}
            ],
            "personInfo.resideAddressProvinceCode": [
                {required: true, message: '请选择省份'}
            ],
            "personInfo.resideAddressCityCode": [
                {required: true, message: '请选择城市'}
            ],
            "personInfo.resideAddressAreaCode": [
                {required: true, message: '请选择地区'}
            ],
            "personInfo.resideAddressDetails": [
                {required: true, message: '请填写详细地址'}
            ],
            "companyInfo.companyName": [
                {required: true, message: '请填写公司名称'}
            ],
            "companyInfo.companyTypeId": [
                {required: true, message: '请选择公司类型'}
            ],
            "companyInfo.businessPlaceId": [
                {required: true, message: '请选择经营场所'}
            ],
            "companyInfo.businessLicenseStatus": [
                {required: true, message: '请选择执照情况'}
            ],
            "companyInfo.monthTurnoverAmount": [
                {required: true, message: '请填写月营业额'}
            ],
            "companyInfo.establishAt": [
                {required: true, message: '请填写成立日期'}
            ],
            "companyInfo.industryTypeId": [
                {required: true, message: '请选择行业Id'}
            ],
            "companyInfo.annualTaxAmount": [
                {required: true, message: '请填写年纳税'}
            ],
            "companyInfo.annualInvoiceAmount": [
                {required: true, message: '请填写年开票'}
            ],
            "assetsHouseInfo.addressDetails": [
                {required: true, message: '请填写详细地址'}
            ],
            "assetsHouseInfo.owner": [
                {required: true, message: '请填写共有人'}
            ],
            "assetsHouseInfo.buyTotalAmount": [
                {required: true, message: '请填写购买价格'}
            ],
            "assetsHouseInfo.buildArea": [
                {required: true, message: '请填写建筑面积'}
            ],
            "assetsHouseInfo.buyType": [
                {required: true, message: '请选择购买方式'}
            ]
        }
    },
    mounted: function () {
        let vmObj = this;
        Ajax.request({
            url: "../common/getOptionValues",
            type: "GET",
            contentType: "application/json",
            async: true,
            successCallback: function (r) {
                vmObj.options = r;
                vmObj.options['maritalArr'] = [
                    {value: "1", label: "已婚"},
                    {value: "2", label: "未婚"},
                    {value: "3", label: "其他"}
                ];
                vmObj.options['applyTypeArr'] = [
                    {value: "1", label: "个人"},
                    {value: "2", label: "企业"},
                ];
                vmObj.options['defArr'] = [
                    {value: "1", label: "个人"},
                    {value: "2", label: "企业"},
                ];
                vmObj.options['insurancePayWayList'] = [
                    {value: "0", label: "月缴"},
                    {value: "1", label: "年缴"},
                ]
            }
        });
        // methods里面定义的方法, 需要赋值给window
        window.details = this.details;
    },
    methods: {
        details: function (id) {
            vm.showList = false;
            vm.loadProvince();
            vm.getInfo(id);
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.show.atAddAction = true;
            vm.show.atUpdateAction = false;
            vm.title = "新增";
            vm.applyInfo = buildDefApplyInfoValueObj();
            vm.show.onlyDetails = false;
            vm.loadProvince();
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.show.onlyDetails = false;
            vm.show.atAddAction = false;
            vm.show.atUpdateAction = true;
            vm.showList = false;
            vm.title = "修改";

            vm.loadProvince();
            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            let url = vm.applyInfo.id == null ? "../applyinfo/save" : "../applyinfo/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.applyInfo),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../applyinfo/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../applyinfo/info/" + id,
                async: true,
                contentType: "application/json",
                successCallback: function (r) {
                    vm.applyInfo = r.applyInfo;
                    vm.dealWithInputArea();
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name, 'mobile': vm.q.mobile},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                mobile: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        dealWithInputArea: function (event) {
            let applyType = vm.applyInfo.applyType;
            if (applyType === "1") {
                vm.show.person = true;
                vm.show.cooperation = false;
            } else {
                vm.show.person = false;
                vm.show.cooperation = true;
            }

        },
        addLoanInfo: function () {
            vm.applyInfo.loanInfoList.push(
                {
                    "applyNo": null,
                    "createAt": null,
                    "id": null,
                    "isDelete": null,
                    "loanAmount": null,
                    "loanBankId": null,
                    "overdueId": null,
                    "promoUserId": null,
                    "surplusAmount": null,
                    "updateAt": null
                }
            );
        },
        removeLoanInfo: function (idx) {
            vm.applyInfo.loanInfoList.splice(idx, 1);
        },
        openUpdateModal: function () {
            vm.show.updateModal = true;
        },
        handleWithOk() {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null || ids.length == 0) {
                return;
            }
            if (vm.updateInfo.promoUserId == null) {
                iview.Message.error("请选择客户经理");
                return;
            }
            let updateInfo = {
                "ids": ids,
                "promoUserId": vm.updateInfo.promoUserId,
            };

            $.ajax({
                url: "../applyinfo/updatePromoUser",
                method: "post",
                data: {
                    "info": JSON.stringify(updateInfo)
                },
                success: function (r) {
                    if (r.code === 0) {
                        vm.show.updateModal = false;
                        vm.reload();
                    } else {
                        iview.Message.error("更新失败,请联系管理员");
                    }
                }
            });
        },
        handleWithCancel: function () {
            vm.show.updateModal = false;
        },
        loadProvince: function () {
            Ajax.request({
                url: "../common/getProvince",
                async: true,
                contentType: "application/json",
                successCallback: function (r) {
                    vm.nativeAreaInfo.provinceList = r;
                    vm.resideAreaInfo.provinceList = r;
                    vm.workCompanyAreaInfo.provinceList = r;
                    vm.houseAreaInfo.provinceList = r;
                }
            });
        },
        loadCity: function (provinceCode, type) {
            Ajax.request({
                url: "../common/getCity/" + provinceCode,
                async: true,
                contentType: "application/json",
                successCallback: function (r) {
                    if (type === 'native') {
                        vm.nativeAreaInfo.cityList = r;
                        vm.nativeAreaInfo.areaList = [];
                    } else if (type === 'reside') {
                        vm.resideAreaInfo.cityList = r;
                        vm.resideAreaInfo.areaList = [];
                    } else if (type === "workCompany") {
                        vm.workCompanyAreaInfo.cityList = r;
                        vm.workCompanyAreaInfo.areaList = [];
                    } else if (type === "house") {
                        vm.houseAreaInfo.cityList = r;
                        vm.houseAreaInfo.areaList = [];
                    }
                }
            });
        },
        loadArea: function (cityCode, type) {
            if (null == cityCode || "" == cityCode) {
                return;
            }

            Ajax.request({
                url: "../common/getArea/" + cityCode,
                async: true,
                contentType: "application/json",
                successCallback: function (r) {
                    if (type === 'native') {
                        vm.nativeAreaInfo.areaList = r;
                    } else if (type === "reside") {
                        vm.resideAreaInfo.areaList = r;
                        vm.show.resideArea = true;
                    } else if (type === "workCompany") {
                        vm.workCompanyAreaInfo.areaList = r;
                        vm.show.workCompanyArea = true;
                    } else if (type === "house") {
                        vm.houseAreaInfo.areaList = r;
                    }
                }
            });
        }
    }
});

function checkInfo() {
    let result = {
        status: false,
        message: "",
    };

    return result;
}

function isEmpty(val) {
    return null == val || undefined == val || "" == val;
}

function buildDefApplyInfoValueObj() {
    return {
        "applyNo": null,
        "applyType": null,
        "assetsCarInfo": {
            "applyNo": null,
            "carBrandId": null,
            "carBuyAt": null,
            "carBuyTotalAmount": null,
            "carBuyType": null,
            "createAt": null,
            "id": null,
            "insuranceCompany": null,
            "insurancePayAmout": null,
            "insurancePayWay": null,
            "isDelete": null,
            "promoUserId": null,
            "updateAt": null
        },
        "assetsCreditInfo": {
            "applyNo": null,
            "createAt": null,
            "creditCardSum": null,
            "creditCardTotalQuota": null,
            "creditCardTotalUseQuota": null,
            "id": null,
            "isDelete": null,
            "promoUserId": null,
            "updateAt": null
        },
        "assetsHouseInfo": {
            "addressAreaCode": null,
            "addressCityCode": null,
            "addressDetails": null,
            "addressProvinceCode": null,
            "applyNo": null,
            "buildArea": null,
            "buyTotalAmount": null,
            "buyType": null,
            "createAt": null,
            "id": null,
            "isDelete": null,
            "loanBankId": null,
            "loanYears": null,
            "monthlySupply": null,
            "owner": null,
            "promoUserId": null,
            "totalHouse": null,
            "totalLoanAmount": null,
            "updateAt": null
        },
        "companyInfo": {
            "annualInvoiceAmount": null,
            "annualTaxAmount": null,
            "applyNo": null,
            "businessLicenseStatus": null,
            "businessPlaceId": null,
            "businessPlaceRent": null,
            "companyName": null,
            "companyTypeId": null,
            "companyTypeOther": null,
            "createAt": null,
            "establishAt": null,
            "id": null,
            "industryTypeId": null,
            "isDelete": null,
            "monthTurnoverAmount": null,
            "promoUserId": null,
            "updateAt": null
        },
        "createAt": null,
        "id": null,
        "isDelete": null,
        "loanInfoList": [],
        "loanPurposeId": "1",
        "loanPurposeOther": null,
        "personInfo": {
            "applyNo": null,
            "createAt": null,
            "id": null,
            "idCardNo": null,
            "isDelete": null,
            "maritalStatus": null,
            "mobile": null,
            "name": null,
            "nativeCityCode": null,
            "nativeProvinceCode": null,
            "promoUserId": null,
            "resideAddressAreaCode": null,
            "resideAddressCityCode": null,
            "resideAddressDetails": null,
            "resideAddressProvinceCode": null,
            "resideTypeId": null,
            "updateAt": null
        },
        "promoUser": null,
        "promoUserId": null,
        "taxInfoList": buildLatestThreeYearTaxInfo(),
        "updateAt": null,
        "workCompanyInfo": {
            "addressAreaCode": null,
            "addressCityCode": null,
            "addressDetails": null,
            "addressProvinceCode": null,
            "applyNo": null,
            "companyName": null,
            "companyPhone": null,
            "createAt": null,
            "department": null,
            "id": null,
            "industryTypeId": null,
            "isDelete": null,
            "post": null,
            "promoUserId": null,
            "updateAt": null
        }
    }
}

function buildLatestThreeYearTaxInfo() {
    let date = new Date;
    let year = date.getFullYear();
    let years = [];

    for (let i = year - 2; i <= year; i++) {
        years.push(
            {
                "taxLevel": null,
                "year": i
            }
        )
    }

    return years;
}